﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using kk.components.contracts;
using kk.messages.contracts.DataModel;

namespace kk.sbadapter
{
    public class SBAdapter : ISaalbestuhlungsAdapter
    {
        public void ProcessBestuhlungZuSaal(Request<string, Saalplan> requestBySaalname)
        {
            var lines = ReadFile(requestBySaalname.RequestData);
            var saalInfo = CalculateSaal(lines);
            var saalPlan = new Saalplan(saalInfo);
            requestBySaalname.ResponsePin(saalPlan);
        }

        internal static string[] ReadFile(string saalName)
        {
            var filePath = "Saal" + saalName + ".txt";
            return File.ReadAllLines(filePath);
        }

        internal static IEnumerable<Platz> CalculateSaal(IEnumerable<string> lines)
        {
            return lines.SelectMany((line, linePosition) => CalculatePlace(line, linePosition, lines.Count()));
        }
     
        internal static IEnumerable<Platz> CalculatePlace(string line, int linePosition, int numberOfLines)
        {
            var reihe = Convert.ToChar((numberOfLines - linePosition) + 64);

            return line
                .Select((ch, charPosition) => new Platz(new Platzposition(reihe, charPosition + 1), ch))
                .Where(platz => platz.PreiskategorieSchlüssel != ' ');
        }
    }
}
